package com.ywz.framework.security.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ywz.common.ResultResp;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 类描述 -> 认证失败处理类
 *
 * @Author: ywz
 * @Date: 2024/07/28
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    /**
     * 方法描述 -> 认证失败处理
     *
     * @Author: ywz
     * @Date: 2024/07/28
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        response.setStatus(200);
        response.setContentType("application/json;charset=UTF-8");
        Map<String, Object> result = new HashMap<>();
        result.put("msg", authException.getMessage());
        result.put("code", ResultResp.UNAUTHORIZED_CODE);
        String s = new ObjectMapper().writeValueAsString(result);
        response.getWriter().println(s);
    }
}